<template>
  <div class="product-detail-container">
    <div class="product-header">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品详情</el-breadcrumb-item>
        <el-breadcrumb-item>{{ product.title }}</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <div class="product-main">
      <div class="product-gallery">
        <!-- 放大镜功能区域 -->
        <div class="magnifier-container">
          <!-- 原图区域 -->
          <div
            class="main-image"
            ref="imageContainer"
            @mousemove="handleMouseMove"
            @mouseleave="isShowZoom = false"
            @mouseenter="isShowZoom = true"
          >
            <img :src="product.image" :alt="product.title" ref="originalImage" />
            <!-- 放大镜框 -->
            <div
              class="magnifier-lens"
              v-show="isShowZoom"
              :style="{
                left: `${lensPosition.x}px`,
                top: `${lensPosition.y}px`,
              }"
            ></div>
          </div>

          <!-- 放大区域 -->
          <div class="zoom-container" v-show="isShowZoom">
            <div
              class="zoom-image"
              :style="{
                backgroundImage: `url(${product.image})`,
                backgroundPosition: `${zoomPosition.x}% ${zoomPosition.y}%`,
              }"
            ></div>
          </div>
        </div>
      </div>

      <div class="product-info">
        <h1 class="product-title">{{ product.title }}</h1>

        <div class="product-meta">
          <div class="price-section">
            <span class="current-price">￥{{ product.price }}</span>
          </div>

          <div class="delivery-info">
            <span class="tag" :style="{ color: '#e4393c', borderColor: 'lightcoral' }">
              {{ product.cityType }}
            </span>
            <span
              class="tag"
              :style="{ color: 'rgb(76, 200, 161)', borderColor: 'rgb(76, 200, 161)' }"
            >
              {{ product.fromType }}
            </span>
          </div>
        </div>

        <div class="product-actions">
          <el-button type="danger" @click="addToCart(product)" size="large"> 加入购物车 </el-button>
          <el-button type="warning" size="large"> 立即购买 </el-button>
        </div>
      </div>
    </div>

    <div class="product-desc">
      <el-tabs v-model="activeTab">
        <el-tab-pane label="商品详情" name="detail">
          <div class="detail-content">
            <!-- 这里可以放商品详情HTML或图片 -->
            <img :src="product.image" :alt="product.title" />
            <p>这里是商品详细描述内容...</p>
          </div>
        </el-tab-pane>
        <el-tab-pane label="规格参数" name="spec">
          <div class="spec-content">
            <el-table :data="specData" border style="width: 100%">
              <el-table-column prop="name" label="参数名称" width="180" />
              <el-table-column prop="value" label="参数值" />
            </el-table>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useCartStore } from '@/stores/cart'

const route = useRoute()
const activeTab = ref('detail')

// 商品数据
const product = ref({
  id: route.params.id || Date.now(), // 确保有ID
  title: route.query.title || '默认商品名称',
  price: route.query.price || '0.00',
  image: route.query.image || '',
  cityType: route.query.cityType || '京东物流',
  fromType: route.query.fromType || '京东自营',
})

// 规格数据
const specData = ref([
  { name: '品牌', value: '示例品牌' },
  { name: '型号', value: '示例型号' },
  { name: '重量', value: '5kg' },
  { name: '产地', value: '中国' },
])

// 使用购物车store
const cartStore = useCartStore()

// 添加到购物车
const addToCart = (product) => {
  // 确保商品数据结构一致
  const cartProduct = {
    id: product.id,
    title: product.title,
    price: product.price,
    image: product.image,
    cityType: product.cityType,
    fromType: product.fromType,
    quantity: 1, // 默认数量为1
    selected: true, // 默认选中
    imageLoaded: false, // 图片加载状态
    imageError: false, // 图片错误状态
  }

  cartStore.addItem(cartProduct)
  ElMessage.success({
    message: '已加入购物车',
    duration: 1000,
  })
}

// 放大镜功能相关变量
const isShowZoom = ref(false)
const imageContainer = ref(null)
const originalImage = ref(null)
const lensPosition = reactive({ x: 0, y: 0 })
const zoomPosition = reactive({ x: 0, y: 0 })
const LENS_SIZE = 100 // 放大镜框的大小

// 处理鼠标移动事件
const handleMouseMove = (e) => {
  if (!imageContainer.value) return

  // 获取图片容器的位置和尺寸
  const rect = imageContainer.value.getBoundingClientRect()

  // 计算鼠标在图片上的相对位置
  let mouseX = e.clientX - rect.left
  let mouseY = e.clientY - rect.top

  // 计算放大镜框的位置（居中于鼠标位置）
  lensPosition.x = Math.max(0, Math.min(mouseX - LENS_SIZE / 2, rect.width - LENS_SIZE))
  lensPosition.y = Math.max(0, Math.min(mouseY - LENS_SIZE / 2, rect.height - LENS_SIZE))

  // 计算放大区域的背景位置百分比
  zoomPosition.x = (lensPosition.x / (rect.width - LENS_SIZE)) * 100
  zoomPosition.y = (lensPosition.y / (rect.height - LENS_SIZE)) * 100
}
</script>

<style lang="scss" scoped>
.product-detail-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background: #fff;
}

.product-header {
  padding: 15px 0;
  border-bottom: 1px solid #f5f5f5;
}

.product-main {
  display: flex;
  padding: 20px 0;
}

.product-gallery {
  width: 450px;
  padding: 15px;

  .magnifier-container {
    display: flex;
    position: relative;
  }

  .main-image {
    width: 100%;
    height: 450px;
    display: flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #f5f5f5;
    position: relative;
    cursor: crosshair;
    overflow: hidden;

    img {
      max-width: 100%;
      max-height: 100%;
    }

    .magnifier-lens {
      position: absolute;
      width: 100px;
      height: 100px;
      border: 1px solid #e4393c;
      background-color: rgba(255, 255, 255, 0.3);
      pointer-events: none;
    }
  }

  .zoom-container {
    position: absolute;
    left: 105%;
    top: 0;
    width: 300px;
    height: 300px;
    border: 1px solid #f5f5f5;
    overflow: hidden;
    z-index: 10;
    background-color: #fff;

    .zoom-image {
      width: 100%;
      height: 100%;
      background-repeat: no-repeat;
      background-size: 300%;
    }
  }
}

.product-info {
  flex: 1;
  padding: 0 30px;

  .product-title {
    font-size: 22px;
    font-weight: 500;
    color: #333;
    margin-bottom: 15px;
  }

  .price-section {
    padding: 15px;
    background: #f5f5f5;
    margin-bottom: 20px;

    .current-price {
      color: #e4393c;
      font-size: 28px;
      font-weight: bold;
    }
  }

  .delivery-info {
    margin-bottom: 20px;

    .tag {
      display: inline-block;
      padding: 2px 8px;
      margin-right: 10px;
      border: 1px solid;
      border-radius: 2px;
      font-size: 12px;
    }
  }
}

.product-actions {
  margin-top: 30px;

  .el-button {
    width: 160px;
    margin-right: 15px;
  }
}

.product-desc {
  margin-top: 30px;
  border-top: 1px solid #f5f5f5;
  padding-top: 20px;

  .detail-content {
    padding: 20px;

    img {
      max-width: 100%;
    }
  }
}
</style>
